const ipList = document.querySelector(".ip-list");
const tip = document.querySelector(".copy_tip");
// const h1 = document.querySelector("h1.href");
const uname = document.querySelector("#uname");
const uport = document.querySelector("#uport");
const radio1 = document.querySelector("#radio1");
const radio2 = document.querySelector("#radio2");
let curName = localStorage.getItem("uname") || "";
let curPort = localStorage.getItem("uport") || "";
let curIsBack = localStorage.getItem("isBack");
let listArr = [];
/**
 * 初始化最新列表数据
 */
const getList = () => {
    fetch("/get-list")
        .then((res) => res.json())
        .then((res) => {
            let arr = JSON.parse(res.data);
            listArr = arr;
            let typeSortedArr = arr.sort((a, b) => a.isBack - b.isBack);
            ipList.innerHTML = typeSortedArr
                .map((v, i) => {
                    let code = getRowCode(v, true);
                    let str = `
                    <div class="row" data-index="${i}">
                    ${code}
                    </div>
                    `;
                    return str;
                })
                .join("");
            document.querySelectorAll(".ip-list .row").forEach((node) => {
                node.addEventListener("click", (e) => {
                    let { target, clientX: left, clientY: top } = e;
                    let { index } = target.dataset;
                    let code = getRowCode(listArr[index], false);
                    copyText(code);
                    showTip(1);
                    tip.style.top = top + "px";
                    tip.style.left = left + "px";
                    let tid = setTimeout(() => {
                        showTip(0);
                        clearTimeout(tid);
                    }, 600);
                });
            });
        });
};
/**
 * 设置输入框以及单选框的值
 */
const setInputInitValue = () => {
    uname.value = curName;
    uport.value = curPort;
    radio1.checked = curIsBack == 1;
    radio2.checked = curIsBack == 0;
};
// const setHref=()=>{
//     const href=`${location.origin}?name=${curName}&port=${curPort}`
//     h1.innerHTML=`<a href="${href}">点击访问${href}并提交ip</a>`
// }
setInputInitValue();
// setHref();
/**
 * 提交
 */
function submitIp() {
    let isBack = radio2.checked ? 0 : 1;
    const href = `${location.origin}?name=${curName}&port=${curPort}&isBack=${isBack}`;
    fetch(href)
        .then((res) => res.json())
        .then((res) => {
            let { data } = res;
            getList();
            alert(`提交成功\n已提交IP:\n${data.newIp}:${data.port}`);
        });
}

/**
 * 监听输入事件并缓存输入结果至 localStorage
 */

uname.addEventListener("input", ({ target }) => {
    let { value } = target;
    localStorage.setItem("uname", value);
    curName = value;
    // setHref()
});
uport.addEventListener("input", ({ target }) => {
    let { value } = target;
    localStorage.setItem("uport", value);
    curPort = value;
    // setHref()
});
radio1.addEventListener("input", ({ target }) => {
    let { checked } = target;
    let val = checked ? 1 : 0;
    localStorage.setItem("isBack", val);
    curIsBack = val;
    // setHref()
});
radio2.addEventListener("input", ({ target }) => {
    let { checked } = target;
    let val = checked ? 0 : 1;
    localStorage.setItem("isBack", val);
    curIsBack = val;
    // setHref()
});
/**
 * @param {1|0} type 是否展示复制成功提示
 */
const showTip = (type) => (tip.style.display = type == 1 ? "block" : "none");
/**
 * 获取拼接tag后的String
 * @param {{apiName, newIp, port, nickname, time,isBack}} obj
 * @param {Boolean} useTag 是否拼接身份类别
 * @returns String
 */
const getRowCode = (obj, useTag) => {
    let { apiName, newIp, port, nickname, time, isBack } = obj;
    const back = isBack == 1;
    const idTag = useTag
        ? `<span class="tag mr-10 ${back ? "back" : "front"}">${
              back ? "后端" : "前端"
          }</span>`
        : "";
    const fullIp = `${newIp}:${port}`;
    let code = back
        ? `let ${apiName} = "${fullIp}/";// ${nickname}  -- ${time}`
        : `${fullIp}(${nickname})`;
    return idTag + code;
};
/**
 * 复制文本
 */
const copyText = (() => {
    // 如果当前浏览器版本不兼容navigator.clipboard
    if (!navigator.clipboard) {
        return (t) =>
            new Promise((resolve, reject) => {
                const ele = document.createElement("input");
                ele.value = t;
                document.body.appendChild(ele);
                ele.select();
                document.execCommand("copy");
                document.body.removeChild(ele);
                if (document.execCommand("copy")) {
                    resolve(1);
                } else {
                    reject(0);
                }
            });
    } else {
        return (t) => navigator.clipboard.writeText(t);
    }
})();

getList();
